import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Solution {
    //合并区间
    public int[][] merge(int[][] intervals) {
        //先根据0位置进行排序
        //1位置数字大于0位置可以合并
        Arrays.sort(intervals,new Comparator<int[]>(){
            public int compare(int[] intervals1,int[] intervals2) {
                return intervals1[0] - intervals2[0];
            }
        });
        List<int[]> merged = new ArrayList<int[]>();
        for (int i = 0; i < intervals.length; ++i) {
            int L = intervals[i][0], R = intervals[i][1];
            if (merged.size() == 0 || merged.get(merged.size() - 1)[1] < L) {
                merged.add(new int[]{L, R});
            } else {
                merged.get(merged.size() - 1)[1] =
                        Math.max(merged.get(merged.size()- 1)[1], R);
            }
        }
        return merged.toArray(new int[merged.size()][]);
    }
}
